<?php
defined( "_SBKH_" ) or die( 'ERROR : RESTRICT ACCESS THIS LOCATION.' );

if(DEBUG == 1){	
	error_reporting(E_ALL);	
	ini_set("display_errors", 1);
}else{
	ini_set("display_errors", 0);
}
function escStr($str = ""){
	$obj = new SBKH();
	$link = $obj ->connectDB();
	if($link){
		return mysql_real_escape_string($str);
	}else{
		return addslashes($str);
	}
}
function pr($array = array()){
	echo '<pre>';
	print_r($array);
	echo '</pre>';
}
function getSES($sessionName = "",$dimension = false, $sign = ":"){	
	$indexs = array();		
	if($dimension == true){
		$indexs = explode($sign, $sessionName);
	}
	$ses = "";
	for($i = 0; $i < count($indexs); $i++){
		$ses .= "['" . $indexs[$i] . "']";
	}echo ($_SESSION['user']['username']);
	$$ses = ltrim(rtrim($ses,"]"),"[");
	die($_SESSION[($$ses)]);
	if(isset($_SESSION[ltrim(rtrim($ses,"["),"]")])){
		return $ses;
	}else{
		return "";
	}
}
function getURL($var = ""){
	if(isset($_GET[$var])){
		return $_GET[$var];	
	}elseif(isset($_POST[$var])){
		return $_POST[$var];	
	}else{
		return "";
	}
}
function getParams(){
	$fullURL = getFullURL();// get URL from address bar
	// Get params step 1
	$URL = $_SERVER['SCRIPT_NAME'] . "?" .  $_SERVER['QUERY_STRING'];
	//$request  = preg_replace("#" . getAction(('url')) . "|\?(.*)#","", $fullURL);echo($fullURL . "<BR>" . $request);
	//echo getAction('url',false) . '<br>';
	$request  = preg_replace("#" . getAction('url',false) . "([\/\?]?.*)#","$1", $fullURL);//echo("0 - " . $fullURL . "<BR>1 - " . ($request));
	$request  = preg_replace("#" . getController('url',false) . "#","", $request);//echo("<BR>2 - " . $request);	
	$request  = preg_replace("#\?.*#","", $request);//echo '<br>3 - ' . $request;
	$params1   = explode("/", $request);
	foreach($params1 as $key => $val){
		if($val == ""){// Prevent outside pass difference prefix (sb_) parameter
			unset($params1[$key]);
		}
	}
	// Get params step 2
	$queryStr = parse_url($fullURL, PHP_URL_QUERY);
	parse_str($queryStr, $params2);
	foreach($params2 as $key => $val){
		if(strpos($key,'sb_') === false){// Prevent outside pass difference prefix (sb_) parameter 
			unset($params2[$key]);
		}
	}
	// Marge all params
	$params = array_merge($params1,$params2);
	//pr($params);die();
	return $params;
}
function getFullURL($host = true){
	$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
	$sp = strtolower($_SERVER["SERVER_PROTOCOL"]);
	$protocol = substr($sp, 0, strpos($sp, "/")) . $s;
	$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
	if($host)
		return $protocol . "://" . $_SERVER['SERVER_NAME'] . $port . $_SERVER['REQUEST_URI'];
	else{
		$con = getController();
		$act = getAction();
		$params = getParams();

		$link = "";
		if($con != ""){
			$link .= $con;
			if($act != "")
				$link .= DS . $act;
		}
		// Assign all params to URL
		$n = true;
		foreach($params as $key => $val){
			if(isNumber($key)){
				$link .= DS . $val;
			}else{
				if($n)
					$link .= "?" . $key . "=" . $val;
				else $link .= "&" . $key . "=" . $val;
				$n = false;
			}
		}
		if($link != "") $link = DS . $link;
		return $link;
	}
}
function getController($var = 'name', $slash = "DS"){
	if($var == 'name'){
		return getURL('controller');
	}elseif($var == 'url'){
		return BASE_URL . getURL('controller') . ($slash !=''?DS:'');
	}
}
function getAction($var = 'name',$slash = "DS"){
	if($var == 'name'){
		return getURL('action');
	}elseif($var == 'url'){
		return getController('url') . getURL('action') . ($slash !=''?DS:'');
	}
}
function isExpire($expire_date = "yyyy-mm-dd h:i:s", $time = false, $format = "24"){
	$timezone = "Asia/Bangkok";
	if(function_exists('date_default_timezone_set')) date_default_timezone_set($timezone);
	if($time) 
		$cur_date = $format == "24"? strtotime(date('Y-m-d H:i:s')) : strtotime(date('Y-m-d h:i:s')) ;
	else
		$cur_date = strtotime(date('Y-m-d'));
	$expire_date = strtotime($expire_date);
	if($cur_date > $expire_date) return true;
}
function hostTracking($promotion_name = ""){
	ini_set ('magic_quotes_gpc', 1);
	$timezone = "Asia/Bangkok";
	if(function_exists('date_default_timezone_set')) date_default_timezone_set($timezone);
	$query_string = $_SERVER['QUERY_STRING'];
	$hostname = $_SERVER['HTTP_REFERER'];
	$remote_host = $_SERVER['REMOTE_ADDR'];
	$server_name = $_SERVER['SERVER_NAME'];
	$php_self = $_SERVER['PHP_SELF'];
	$user_agent= $_SERVER['HTTP_USER_AGENT'];
	
	if ( $parts = parse_url($hostname ) ) {
		$tmp = strpos($parts["host"],'www.');
		if($tmp === false)
			$hostname = $parts["scheme"] . "://" . 'www.' . $parts["host"];
		else 
			$hostname = $parts["scheme"] . "://" . $parts["host"];
		$query="Insert Into track_source_ads SET
		`promotion_name` = '" . esc_str($promotion_name) . "',
		`query_string` = '" . esc_str($query_string) . "',
		`hostname` = '" . esc_str($hostname) . "',
		`remote_host` = '" . esc_str($remote_host) . "',		
		`server_name` = '$server_name',
		`php_self`= '$php_self',
		`user_agent`= '$user_agent',
		`http_referer` = '" . $_SERVER["HTTP_REFERER"] . "',
			`date` = '" . date('Y-m-d H:i:s') . "'";
		$obj = new SKH();
		$result = $obj->query( $query);
		return $result;
	}else return false;
}
function getCountryNameByIP($ip = ""){
	$ip=$ip == ""?$_SERVER['REMOTE_ADDR']:$ip;
	$addr_details = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$ip));
	$city = stripslashes(ucfirst($addr_details['geoplugin_city']));
	$countrycode = stripslashes(ucfirst($addr_details['geoplugin_countryCode']));
	$country = stripslashes(ucfirst($addr_details['geoplugin_countryName']));
	//die(pr($addr_details));
	return $country;
}
/*
 * $data : length must be <= 60 to be match with $pre which has 29 elements
 * if want more then 60 character must be add more element to $pre
 * 3 characters need to add 2 element to $pre
 * */
function b64encode($data = ""){ // strlen($data) must be <= 60
	$pre = array("S","A","M","S","A","M","B","O","S","K","H","2","0","0","5","8","8","2","0","1","3","0","9","3","0","P", "M", "S"); // 29 elements
	$first_ncode = base64_encode($data);
	$data = "";
	$j = 0;
	$end = 3;
	for($i = 0; $i< strlen($first_ncode); $i+=3){
		$str = "";
		$str = substr($first_ncode,$i,$end);
		$str .= $pre[$j];
		$data .= $str;
		$j++;
	}
	return base64_encode($data);
}
function b64decode($data = ""){
	$pre = array("S","A","M","S","A","M","B","O","S","K","H","2","0","0","5","8","8","2","0","1","3","0","9","3","0","P", "M", "S");
	$first_ncode = base64_decode($data);
	$data = "";
	$j = 0;
	$end = 3;
	for($i = 0; $i< strlen($first_ncode); $i+=4){
		$str = "";
		$str = substr($first_ncode,$i,$end);
		$data .= $str;
	}
	return base64_decode($data);
}
function isMobile(){
	//Mobile Detection
	$ipad = strpos($_SERVER['HTTP_USER_AGENT'],"iPad");
	$iphone = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
	$android = strpos($_SERVER['HTTP_USER_AGENT'],"Android");
	$palmpre = strpos($_SERVER['HTTP_USER_AGENT'],"webOS");
	$berry = strpos($_SERVER['HTTP_USER_AGENT'],"BlackBerry");
	$ipod = strpos($_SERVER['HTTP_USER_AGENT'],"iPod");
	$symbian = strpos($_SERVER['HTTP_USER_AGENT'],"Symbian");

	if ($ipad || $iphone || $android || $palmpre || $ipod || $berry || $symbian == true) return true;
	else return false;
}
function getDevice(){
	require_once VENDOR . "mobileDetect.php";
	$detect = new Mobile_Detect();
	$device_type = ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'phone') : 'computer');
	return $device_type;
}
function isPhoneNumber($str = ""){
	if($str == "") return true;
	$pattern = "/^[()0-9-+\s]+$/";
	if(preg_match($pattern,$str)) return true;
	else return false;
}
function isEmail($str = ""){
	$pattern = "/^([a-zA-Z0-9_\.\-]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4})?$/";
	if(preg_match($pattern,$str)) return true;
	else return false;
}
function isNumber($str = ""){
	$pattern = "/^[0-9]+$/";
	if(preg_match($pattern,$str)) return true;
	else return false;
}
function isDateTime($str = "",$noTime = true){//Wed, 19-Jun-2013 08:40:54 AM
	if($noTime){
		$pattern = "/^[a-z]+,\s[0-9]{1,2}-[a-z0-9]{2,4}-[0-9]{2,4}|^[0-9]{1,2}-[a-z0-9]{2,4}-[0-9]{2,4}|[0-9]{4}-[0-9]{2}-[0-9]{2}/i";
	}
	else{ 
		$pattern = "/^[a-z]+,\s[0-9]{1,2}-[a-z0-9]{2,4}-[0-9]{2,4}\s[0-9]{2}:[0-9]{2}:[0-9]{2}\s[amp]{2}$|^[0-9]{1,2}-[a-z0-9]{2,4}-[0-9]{2,4}\s[0-9]{2}:[0-9]{2}:[0-9]{2}\s[amp]{2}$|[0-9]{4}-[0-9]{2}-[0-9]{2}/i";		
	}
	if(preg_match($pattern,$str)) return true;
	else return false;
}
function internetConnected(){
	$conn = @fsockopen("www.google.com", 80, $errno, $errstr, 30);
        if ($conn)
        {
           $status = true;
           fclose($conn);
        }
        else
        {
           $status = false;
           //$status .= "$errstr ($errno)";
        }
        return $status;
}
function pagination($page_number= 1,$limit_start = 0, $limit_end = 15, $number_of_rows = 1, $id = ""){
	$html = '
	<div class="pagination pagination-right">';
	$controller = getController();
	$action = DS .  (getAction() != ""?getAction():"index");
	$link = BASE_URL . $controller;

	$link_first = (getAction() != ""?$link . $action : $link) . ($id != ""?(DS . $id) : "");

	$page_previous = $page_number >= 2?$page_number-1:"";
	$link_previous = $page_previous != ""?($link . $action . DS) . ($id != ""?( $id . DS):"") . $page_previous : "#";

	$page_next = (ceil($number_of_rows/$limit_end) > $page_number)?$page_number+1:"";
	$link_next = $page_next != ""?($link . $action . DS) . ($id != ""?($id . DS):"") . $page_next : "#";

	$link_last = ceil($number_of_rows/$limit_end) > 0?($link . $action . DS) . ($id != ""?($id . DS):"") . ceil($number_of_rows/$limit_end):"#";

	$current_row = $limit_end * $page_number - $limit_end + 1;
	$to_row = ($limit_end * $page_number) > $number_of_rows? $number_of_rows: ($limit_end * $page_number);

	$html .= '
			<ul>
				<li><a href="' . $link_first . '" title="Preview first page of results" class="a-pagination first">First</a></li>
				<li><a href="' . $link_previous . '" title="Preview previous page of results" class="a-pagination previous">Previous</a></li>
				<li class="active"><a>' . $page_number . ' of '. ceil($number_of_rows/$limit_end) . ' | ' . $number_of_rows . ' rows</a></li>
				<li><a href="' . $link_next . '" title="View next page of results" class="a-pagination next">Next</a></li>
				<li><a href="' . $link_last . '" title="View last page of results" class="a-pagination last">Last</a></li>
			</ul>
	</div>';
	return $html;
}
function dayEN2KH($day){
	$days = array( "Monday" => 'ច័ន្ទ', 'Tuesday' => 'អង្គារ', 'Wednesday' => 'ពុធ', 'Thursday' => 'ព្រហស្បតិ៍', 'Friday' => 'សុក្រ', 'Saturday' => 'សៅរ៍', 'Sunday' => 'អាទិត្យ');
	if(isset($days[$day]))
		return "ថ្ងៃ" . $days[$day];
	else return $day;
}
function monthEN2KH($month){
	$months = array( "January" => 'មករា', 'February' => 'កុម្ភះ', 'March' => 'មិនា', 'April' => 'មេសា', 'May' => 'ឧសភា', 'June' => 'មិថុនា', 'July' => 'កក្កដា', 'August' => 'សីហា', 'September' => 'កញ្ញា', 'October' => 'តុលា', 'November' => 'វិច្ឆិកា', 'December' => 'ធ្នូ');
	if(isset($months[$month]))
		return $months[$month];
	else return $month;
}
function numEN2KH($num = ""){
	$len = strlen($num);
	$kh_numbers = array("0" => "០","1" => "១", "2" => "២", "3" => "៣", "4" => "៤", "5" => "៥", "6" => "៦", "7" => "៧", "8" => "៨", "9" => "៩");
	$tmp = "";
	for($i = 0; $i < $len; $i++){
		$cur = substr($num,$i,1);
		$tmp .= $kh_numbers[$cur];
	}	
	return $tmp;
}
function numKH2EN($num = ""){
	$len = strlen($num);
	$en_numbers = array("០" => "0","១" => "1", "២" => "2", "៣" => "3", "៤" => "4", "៥" => "5", "៦" => "6", "៧" => "7", "៨" => "8", "៩" => "9");
	$tmp = "";
	for($i = 0; $i < $len; $i++){
		$cur = substr($num,$i,1);
		$tmp .= $en_numbers[$cur];
	}
	return $tmp;
}
function getImage($string = "",$width = 105, $height = 20){
	header("Content-type: image/png");
	$im = @imagecreate($width, $height)
	or die("Cannot Initialize new GD image stream");
	$background_color = imagecolorallocate($im, 255, 255, 255);
	$text_color = imagecolorallocate($im, 99, 99, 99);
	imagestring($im, 1, 5, 5,  $string, $text_color);
	imagepng($im);
	imagedestroy($im);
	return $im;
}

function getElement($element, $ext = "php"){
	require_once ELEMENT . str_replace('-','_',$element) . DOT . $ext;
}
function getElementParent($element, $ext = "php"){
	require_once "../" . ELEMENT . str_replace('-','_',$element) . DOT . $ext;
}
?>